<?php
/**
 * 城市维护
 * User: cxm
 * Date: 2019/11/11
 * Time: 16:01
 */
namespace App\Http\Controllers\Admin\System;

use App\Http\Controllers\Admin\Controller;
use App\Models\Region;
use Illuminate\Http\Request;
use DB,Validator;
class CityController extends Controller {
    /**
     * 获取城市列表
     * URL GET:/admin/city/get-lists
     * @param Request $request
     * @param string start_time 搜索开始时间
     * @param string end_time 搜索结束时间
     * @param string keyword 搜索关键字
     * @param int pid 父级ID
     * @param int page 页码
     * @param int limit 每页显示条数
     * @return mixed
     */
    public function getLists (Request $request) {
        $params = $request->only(['start_time','end_time','keyword','pid','page','limit']);
        // 搜索条件
        $where = [];
        // 父级条件查询  默认为0
        $pid = isset($params['pid']) ? $params['pid'] : 0;
        $where[] = ['parent_id',$pid];
        // 添加时间搜索
        $start_time = isset($params['start_time']) ? $params['start_time'] : '';
        $end_time = isset($params['end_time']) ? $params['end_time'] : '';
        if (!empty($start_time)) {
            $where[] = ['created_at','>=',$start_time];
        }
        if (!empty($end_time)) {
            $where[] = ['created_at','<=',$end_time];
        }
        // 关键字搜索
        $keyword = isset($params['keyword']) ? $params['keyword'] : '';
        if (!empty($keyword)) {
            $where[] = ['name','like','%'.$keyword.'%'];
        }
        // 排序
        $orderBy = [['sort','asc'],['created_at','desc']];
        // 请求数据
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : config('rhzc.pageSize');
        $data = Region::getData($where,$orderBy,$page,$limit);
        // 查询上级ID
        $parent_id = Region::findFatherId($pid);
        $data['parent_id'] = !isset($parent_id) ?  -1 : $parent_id ;
        return $this->success('查询成功',$data);
    }

    /**
     * 城市添加编辑
     * URL POST:/admin/city/store
     * @param Request $request
     * @param int id 城市ID 编辑时传
     * @param int pid 父ID
     * @param string name 城市名称
     * @param string py 拼音
     * @param string zip_code 邮编
     * @param string code 区号
     * @return mixed
     * @throws
     */
    public function store(Request $request){
        $params = $request->only(['id','pid','name','short_name','initials','sort']);
        $id = isset($params['id']) ? $params['id'] : 0;
        $validator = Validator::make($params,[
            'name'      => ['required']
        ],[
            'name.required' => '名称不能为空'
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        if ($id == 0) {
            $region = new Region();
        }else{
            $region = Region::find($id);
            if (!$region) {
                return $this->error('地区不存在');
            }
        }
        DB::beginTransaction();
        try{
            $region->parent_id      = isset($params['pid']) ? $params['pid'] : 0;
            $region->name           = $params['name'];
            $region->short_name     = isset($params['short_name']) ? $params['short_name'] : '';
            $region->initials       =isset($params['initials']) ? $params['initials'] : '';
            $region->sort           = isset($params['sort']) ? $params['sort'] : '';
            if ($region->save()) {
                // 更新level和path字段
                $this->refreshRegion($region->id);
            }

            // 保存城市信息到文件
            //Region::exportAll2Json();
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success('操作成功');
    }

    /**
     * 修改地区的pid和level字段
     * @param $id
     */
    public function refreshRegion($id)
    {
        $region     = new Region(); // 实例化User对象
        $cate         = $region->where("id", $id)->first()->toArray(); // 找出他自己
        $table_prefix = DB::getTablePrefix();// 表前缀
        // 刚新增的分类先把它的值重置一下
        if ($cate['path'] == '') {
            ($cate['parent_id'] == 0) && DB::update("UPDATE {$table_prefix}region set  path = '0,$id', level = 1 where id = $id"); // 如果是一级分类
            DB::update("UPDATE {$table_prefix}region AS a ,{$table_prefix}region AS b SET a.path = CONCAT_WS(',',b.path,'$id'),a.level = (b.level+1) WHERE a.parent_id=b.id AND a.id = $id");
            $cate = $region->where("id", $id)->first()->toArray(); // 从新找出他自己
        }

        if ($cate['parent_id'] == 0) { //有可能是顶级分类 他没有老爸
            $parent_cat['path']  = '0';
            $parent_cat['level'] = 0;
        } else {
            $parent_cat = $region->where("id", $cate['parent_id'])->first()->toArray(); // 找出他老爸的parent_id_path
        }
        $replace_level = $cate['level'] - ($parent_cat['level'] + 1); // 看看他 相比原来的等级 升级了多少  ($parent_cat['level'] + 1) 他老爸等级加一 就是他现在要改的等级
        $replace_str   = $parent_cat['path'] . ',' . $id;
        DB::update("UPDATE `{$table_prefix}region` SET path = REPLACE(path,'{$cate['path']}','$replace_str'), level = (level - $replace_level) WHERE  path LIKE '{$cate['path']}%'");
    }

    /**
     * 删除
     * URL POST:/admin/city/delete
     * @param Request $request
     * @param array ids 删除ID
     * @return mixed
     */
    public function delete(Request $request){
        $params = $request->only(['ids']);
        if (!array_key_exists('ids',$params)) {
            return $this->error('缺少城市ID');
        }
        $data = Region::whereIn('id',$params['ids'])->delete();
        if (!$data) {
            return $this->error('删除失败');
        }
        return $this->success('删除成功');
    }

    /**
     * 保存城市到文件
     * URL POST:/admin/city/export
     * @param Request $request
     * @param type 1all 2 市级
     * @return mixed
     */
    public function getRegion(Request $request){
        $type = $request->post('type',1);
        set_time_limit(0);
        switch($type){
            case 1:
                Region::exportAll2Json();
                break;
            case 2: // 市级级推荐
                Region::exportProvinceAndHotJson();
                break;
            default: // 全部
                Region::exportAll2Json();
                Region::exportProvinceAndHotJson();
                break;
        }
        return $this->success('更新成功');
    }

    /**
     * 获取所有的城市
     * URL POST:/admin/city/allData
     * @return mixed
     */
    public function getAll(){
        set_time_limit(0);
        $first = [
            "value" => 0,
            "label" => "顶级菜单",
            "children" => []
        ];
        $data = Region::dataGroup();
        array_unshift($data,$first);
        return $this->success('查询成功',$data);
    }

    /**
     * 修改排序
     * URL POST:/admin/city/updateSort
     * @param Request $request
     * @param int id 主营业务ID
     * @param int sort 排序值
     * @return mixed
     */
    public function updateSort(Request $request){
        $params =$request->only(['id','sort']);
        if (!array_key_exists('id',$params) || empty($params['id'])) {
            return $this->error('缺少主营业务ID');
        }
        $sort = isset($params['sort']) ? $params['sort'] : 1;
        $detail = Region::find($params['id']);
        if (!$detail) {
            return $this->error('主营业务不存在');
        }
        $where = [];
        $where[] = ['id',$params['id']];
        $field = ['sort'=>$sort];
        $result = Region::modify($where,$field);
        if ($result === false) {
            return $this->error('修改失败');
        }
        return $this->success('修改成功');
    }
}